package com.kmzx.one.project.service.impl;

import com.kmzx.one.project.config.data.WXDataConfig;
import com.kmzx.one.project.config.wx.WxPayProperties;
import com.kmzx.one.project.others.common.WxSeaGateResponse;
import com.kmzx.one.project.service.SeaGateService;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.Header;
import org.apache.http.HttpHeaders;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.message.BasicHeader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import weixin.popular.client.LocalHttpClient;

import java.nio.charset.Charset;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;

@Service
public class SeaGateServiceImpl implements SeaGateService {

    @Autowired
    private WxPayProperties properties;

    @Autowired
    private WXDataConfig wxDataConfig;


    @Override
    public void reportWXGate(String orderCodes, String wxOrderCodes) {
        SortedMap<String, Object> sortMap = new TreeMap<>();

        // 公众账号ID
        sortMap.put("appid", properties.getAppId());
        // 商户号
        sortMap.put("mch_id", properties.getMchId());
        // 海关名
        sortMap.put("customs", properties.getCustoms());
        // 海关号码
        sortMap.put("mch_customs_no", properties.getMchCustomsNo());
        // ADD 新增报关申请
        // MODIFY 修改
        sortMap.put("action_type", "ADD");
        // 商户订单号
        sortMap.put("out_trade_no", orderCodes);
        // 微信支付订单号
        sortMap.put("transaction_id", wxOrderCodes);

        sortMap.put("sub_order_no", orderCodes);
        sortMap.put("fee_type", "CNY");
        sortMap.put("order_fee", "25200");
        sortMap.put("transport_fee", "0");
        sortMap.put("product_fee", "25200");

        StringBuilder strb = new StringBuilder();


        Set<String> keySet = sortMap.keySet();
        for (String key : keySet) {
            Object value = sortMap.get(key);
            strb.append(key).append("=").append(value);
            strb.append("&");
        }

        strb.append("key=").append(properties.getMchKey());

        String signStr = DigestUtils.md5Hex(strb.toString()).toUpperCase();

//        sortMap.put("sign", signStr);

//        WxSeaGateRequest gateRequest = new WxSeaGateRequest();
//        gateRequest.setAppid(properties.getAppId())
//                .setMchId(properties.getMchId())
//                .setOutTradeNo(orderCodes)
//                .setTransactionId(wxOrderCodes)
//                .setCustoms(properties.getCustoms())
//                .setMchCustomsNo(properties.getMchCustomsNo())
//                .setActionType("ADD");
//        gateRequest.setSign(signStr);

//        XStream xstream = XStreamInitializer.getInstance();
//        //涉及到服务商模式的两个参数，在为空值时置为null，以免在请求时将空值传给微信服务器
//        xstream.processAnnotations(gateRequest.getClass());
//        String toStrXml = xstream.toXML(gateRequest);

        StringBuilder xmlRequest = new StringBuilder();
        xmlRequest.append("<xml>")
                .append("<appid>")
                .append(properties.getAppId())
                .append("</appid>")
                .append("<mch_id>")
                .append(properties.getMchId())
                .append("</mch_id>")
                .append("<out_trade_no>")
                .append(orderCodes)
                .append("</out_trade_no>")
                .append("<transaction_id>")
                .append(wxOrderCodes)
                .append("</transaction_id>")
                .append("<customs>")
                .append(properties.getCustoms())
                .append("</customs>")
                .append("<mch_customs_no>")
                .append(properties.getMchCustomsNo())
                .append("</mch_customs_no>")
                .append("<action_type>")
                .append("ADD")
                .append("</action_type>")


                .append("<sign>")
                .append(signStr)
                .append("</sign>")

                .append("<sub_order_no>")
                .append(orderCodes)
                .append("</sub_order_no>")

                .append("<fee_type>")
                .append("CNY")
                .append("</fee_type>")

                .append("<order_fee>")
                .append("25200")
                .append("</order_fee>")

                .append("<transport_fee>")
                .append("0")
                .append("</transport_fee>")


                .append("<product_fee>")
                .append("25200")
                .append("</product_fee>")


                .append("</xml>");

        System.out.println("xmlRequest.toString() = " + xmlRequest.toString());


        HttpUriRequest httpUriRequest = getHttpUriRequest(xmlRequest.toString());
        WxSeaGateResponse result = LocalHttpClient.executeXmlResult(httpUriRequest, WxSeaGateResponse.class);

    }

    @Override
    public void searchWXGate(String orderCodes, String wxOrderCodes) {
        SortedMap<String, Object> sortMap = new TreeMap<>();

        // 公众账号ID
        sortMap.put("appid", properties.getAppId());
        // 商户号
        sortMap.put("mch_id", properties.getMchId());
        // 海关名
        sortMap.put("customs", properties.getCustoms());
        // 海关号码
//        sortMap.put("mch_customs_no", properties.getMchCustomsNo());
        // ADD 新增报关申请
        // MODIFY 修改
//        sortMap.put("action_type", "ADD");
        // 商户订单号
        sortMap.put("out_trade_no", orderCodes);
        // 微信支付订单号
//        sortMap.put("transaction_id", wxOrderCodes);
//
//        sortMap.put("sub_order_no", orderCodes);
//        sortMap.put("fee_type", "CNY");
//        sortMap.put("order_fee", "25200");
//        sortMap.put("transport_fee", "0");
//        sortMap.put("product_fee", "25200");

        StringBuilder strb = new StringBuilder();


        Set<String> keySet = sortMap.keySet();
        for (String key : keySet) {
            Object value = sortMap.get(key);
            strb.append(key).append("=").append(value);
            strb.append("&");
        }

        strb.append("key=").append(properties.getMchKey());

        String signStr = DigestUtils.md5Hex(strb.toString()).toUpperCase();


        StringBuilder xmlRequest = new StringBuilder();
        xmlRequest.append("<xml>")
                .append("<appid>")
                .append(properties.getAppId())
                .append("</appid>")
                .append("<mch_id>")
                .append(properties.getMchId())
                .append("</mch_id>")
                .append("<out_trade_no>")
                .append(orderCodes)
                .append("</out_trade_no>")

                .append("<customs>")
                .append(properties.getCustoms())
                .append("</customs>")

                .append("<sign>")
                .append(signStr)
                .append("</sign>")

                .append("</xml>");

        System.out.println("xmlRequest.toString() = " + xmlRequest.toString());


        HttpUriRequest httpUriRequest = getSearchHttpUriRequest(xmlRequest.toString());
        WxSeaGateResponse result = LocalHttpClient.executeXmlResult(httpUriRequest, WxSeaGateResponse.class);

    }

    @Override
    public void reReportWxGate(String orderCodes, String wxOrderCodes) {
        SortedMap<String, Object> sortMap = new TreeMap<>();

        // 公众账号ID
        sortMap.put("appid", properties.getAppId());
        // 商户号
        sortMap.put("mch_id", properties.getMchId());
        // 海关名
        sortMap.put("customs", properties.getCustoms());
        // 海关号码
        sortMap.put("mch_customs_no", properties.getMchCustomsNo());
        // ADD 新增报关申请
        // MODIFY 修改
//        sortMap.put("action_type", "ADD");
        // 商户订单号
        sortMap.put("out_trade_no", orderCodes);
        // 微信支付订单号
//        sortMap.put("transaction_id", wxOrderCodes);


        StringBuilder strb = new StringBuilder();


        Set<String> keySet = sortMap.keySet();
        for (String key : keySet) {
            Object value = sortMap.get(key);
            strb.append(key).append("=").append(value);
            strb.append("&");
        }

        strb.append("key=").append(properties.getMchKey());

        String signStr = DigestUtils.md5Hex(strb.toString()).toUpperCase();

//        sortMap.put("sign", signStr);

//        WxSeaGateRequest gateRequest = new WxSeaGateRequest();
//        gateRequest.setAppid(properties.getAppId())
//                .setMchId(properties.getMchId())
//                .setOutTradeNo(orderCodes)
//                .setTransactionId(wxOrderCodes)
//                .setCustoms(properties.getCustoms())
//                .setMchCustomsNo(properties.getMchCustomsNo())
//                .setActionType("ADD");
//        gateRequest.setSign(signStr);

//        XStream xstream = XStreamInitializer.getInstance();
//        //涉及到服务商模式的两个参数，在为空值时置为null，以免在请求时将空值传给微信服务器
//        xstream.processAnnotations(gateRequest.getClass());
//        String toStrXml = xstream.toXML(gateRequest);

        StringBuilder xmlRequest = new StringBuilder();
        xmlRequest.append("<xml>")
                .append("<appid>")
                .append(properties.getAppId())
                .append("</appid>")

                .append("<mch_id>")
                .append(properties.getMchId())
                .append("</mch_id>")

                .append("<out_trade_no>")
                .append(orderCodes)
                .append("</out_trade_no>")


                .append("<customs>")
                .append(properties.getCustoms())
                .append("</customs>")

                .append("<mch_customs_no>")
                .append(properties.getMchCustomsNo())
                .append("</mch_customs_no>")


                .append("<sign>")
                .append(signStr)
                .append("</sign>")

                .append("</xml>");

        System.out.println("xmlRequest.toString() = " + xmlRequest.toString());


        HttpUriRequest httpUriRequest = reStartHttpUriRequest(xmlRequest.toString());
        WxSeaGateResponse result = LocalHttpClient.executeXmlResult(httpUriRequest, WxSeaGateResponse.class);
    }

    @Override
    public void reportSeaGate() {

    }

    @Override
    public void reportProxy() {

    }

    protected static Header xmlHeader = new BasicHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_XML.toString());

    public HttpUriRequest getHttpUriRequest(String xmlStringContent) {
        HttpUriRequest httpUriRequest = RequestBuilder.post()
                .setHeader(xmlHeader)
                .setUri(wxDataConfig.getSeaGateUrl())
                .setEntity(new StringEntity(xmlStringContent, Charset.forName("utf-8")))
                .build();
        return httpUriRequest;
    }

    public HttpUriRequest getSearchHttpUriRequest(String xmlStringContent) {
        HttpUriRequest httpUriRequest = RequestBuilder.post()
                .setHeader(xmlHeader)
                .setUri("https://api.mch.weixin.qq.com/cgi-bin/mch/customs/customdeclarequery")
                .setEntity(new StringEntity(xmlStringContent, Charset.forName("utf-8")))
                .build();
        return httpUriRequest;
    }


    public HttpUriRequest reStartHttpUriRequest(String xmlStringContent) {
        HttpUriRequest httpUriRequest = RequestBuilder.post()
                .setHeader(xmlHeader)
                .setUri("https://api.mch.weixin.qq.com/cgi-bin/mch/newcustoms/customdeclareredeclare")
                .setEntity(new StringEntity(xmlStringContent, Charset.forName("utf-8")))
                .build();
        return httpUriRequest;
    }


}
